package com.weiaibenpao.demo.chislim.ui.marathon;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.bean.LaunchBean;
import com.weiaibenpao.demo.chislim.bean.UserBean;
import com.weiaibenpao.demo.chislim.model.MyModel;
import com.weiaibenpao.demo.chislim.sport.bean.ProvinceBean;
import com.weiaibenpao.demo.chislim.sport.utils.JsonProvinceUtils;
import com.weiaibenpao.demo.chislim.ui.MatchDetailActivity;
import com.weiaibenpao.demo.chislim.util.DateUtil;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CampaignActivity extends AppCompatActivity {

    @BindView(R.id.sportDate)
    TextView sportDate;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.run_theme)
    TextView runTheme;
    @BindView(R.id.et_theme)
    EditText etTheme;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.et_area)
    TextView etArea;
    @BindView(R.id.et_number)
    EditText etNumber;
    @BindView(R.id.et_start_time)
    TextView etStartTime;
    @BindView(R.id.et_end_time)
    TextView etEndTime;
    @BindView(R.id.check_disclaimer)
    CheckBox checkDisclaimer;
    @BindView(R.id.tv_disclaimer)
    TextView tvDisclaimer;
    @BindView(R.id.btn_launch)
    Button btnLaunch;
    @BindView(R.id.image_area)
    ImageView imageArea;
    @BindView(R.id.image_start)
    ImageView imageStart;
    @BindView(R.id.image_end)
    ImageView imageEnd;
    @BindView(R.id.tv_area_distance)
    TextView tvAreaDistance;
    @BindView(R.id.tv_user_distance)
    TextView tvUserDistance;
    @BindView(R.id.scroll_view)
    ScrollView scrollView;
    private boolean isScroll;
    private OptionsPickerView pvOptions;
    private int num1, num2, num3;
    private ArrayList<ProvinceBean> options1Items;
    private ArrayList<ArrayList<String>> options2Items;
    private ArrayList<ArrayList<ArrayList<String>>> options3Items;
    private JsonProvinceUtils jsonProvinceUtils;
    private String provinceName, cityName, districtName;
    private double perimeter = 0;
    DecimalFormat decimalFormat = new DecimalFormat("0.00");
    private long startTime, endTime, nowTime;
    private String num;
    private boolean isAgree = false;
    WeakReference<Activity> weakReference = new WeakReference<Activity>(this);
    Context context;
    private String selectCity;
    private String code;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_campaign);
        ButterKnife.bind(this);
        context = weakReference.get();
        initView();

    }

    public static void openActivity(Context context) {
        Intent intent = new Intent(context, CampaignActivity.class);
        context.startActivity(intent);
    }

    private void initView() {
        jsonProvinceUtils = new JsonProvinceUtils(this);
        jsonProvinceUtils.initJsonData();
        options1Items = jsonProvinceUtils.getOptions1Items();
        options2Items = jsonProvinceUtils.getOptions2Items();
        options3Items = jsonProvinceUtils.getOptions3Items();
        tvDisclaimer.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        checkDisclaimer.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isAgree = isChecked;
                tvDisclaimer.setSelected(isChecked);
            }
        });
        etNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                num = etNumber.getText().toString();
                showUserDis();
            }
        });
        if (etContent.isSelected()) {
            isScroll = true;
        } else {
            isScroll = false;
        }
        scrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return isScroll;
            }
        });

        etContent.setOnTouchListener(new View.OnTouchListener() {//added by zjl for fixing scroll conflict
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.getParent().requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });
    }

    @OnClick({R.id.back, R.id.et_area, R.id.tv_disclaimer, R.id.number_layout, R.id.et_start_time, R.id.et_end_time, R.id.btn_launch})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.et_area:
                showPickerView();
                break;
            case R.id.number_layout:

                break;
            case R.id.et_start_time:
                showTimePicker(0);
                break;
            case R.id.et_end_time:
                showTimePicker(1);
                break;
            case R.id.tv_disclaimer:
                startActivity(new Intent(context, DisclaimerActivity.class));
                break;

            case R.id.btn_launch:
                launchActivity();
                break;


        }
    }

    /**
     * 确认发起活动
     */
    private void launchActivity() {
        String mName = etName.getText().toString();
        String mPhone = etPhone.getText().toString();
        String mContent = etContent.getText().toString();
        String mTheme = etTheme.getText().toString();


        if (TextUtils.isEmpty(mName)) {
            Toast.makeText(context, "请输入名字", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(mPhone)) {
            Toast.makeText(context, "请输手机号码", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(mTheme)) {
            Toast.makeText(context, "请输入活动主题", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(mContent)) {
            Toast.makeText(context, "请输入活动描述", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(selectCity)) {

            Toast.makeText(context, "请输入团队跑行政区", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(num)) {
            Toast.makeText(context, "请输入参赛人数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (startTime == 0) {
            Toast.makeText(context, "请输入活动开始时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (endTime == 0) {
            Toast.makeText(context, "请输入活动结束时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!isAgree) {
            Toast.makeText(context, "请阅读免责申明并同意", Toast.LENGTH_SHORT).show();
            return;
        }
        showOver(mName, mPhone, mContent, mTheme);

    }

    /**
     * 跑步完成显示
     */
    private void showOver(final String mName, final String mPhone, final String mContent, final String mTheme) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = LayoutInflater.from(this).inflate(R.layout.game_launch, null);
        view.findViewById(R.id.close_run).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        view.findViewById(R.id.btn_commit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commit(mName, mPhone, mContent, mTheme);
                dialog.dismiss();
            }
        });
        dialog.setView(view);
        dialog.show();

    }

    private void commit(String mName, String mPhone, String mContent, String mTheme) {
        MyModel.getModel().getService().launnchGame(UserBean.getUserBean().userId,
                mName, mPhone, mTheme, mContent, provinceName, cityName, districtName,
                perimeter, Integer.parseInt(num), perimeter / Integer.parseInt(num), startTime, endTime, code).enqueue(new Callback<LaunchBean>() {
            @Override
            public void onResponse(Call<LaunchBean> call, Response<LaunchBean> response) {
                Log.e("wlx33", "00000: " + new Gson().toJson(response.body()));
                if (response.body() != null) {
                    if (response.body().getCode() == 0) {
                        if (response.body().getData() != null) {
                            int id = response.body().getData().getActivityMap().getId();
                            MatchDetailActivity.openActivity(context, id);
                            finish();
                        }
                    }
                } else {
                    Toast.makeText(context, "请求失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<LaunchBean> call, Throwable throwable) {
                Toast.makeText(context, throwable.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * @param type type=0 开始时间
     *             type=1 结束时间
     */
    private void showTimePicker(final int type) {
        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {


            @Override
            public void onTimeSelect(Date date, View view) {
                if (type == 0) {
                    nowTime = System.currentTimeMillis();
                    startTime = date.getTime();
                } else if (type == 1) {
                    endTime = date.getTime();
                    Log.e("wlx", "endTime: " + endTime + "  startTime:" + startTime);

                }
                if (startTime != 0 && endTime != 0) {
                    if (startTime >= nowTime && startTime < endTime) {
                        if (type == 0) {
                            etStartTime.setText(DateUtil.DateToStr(date));
                            imageStart.setVisibility(View.GONE);
                        } else if (type == 1) {
                            etEndTime.setText(DateUtil.DateToStr(date));
                            imageEnd.setVisibility(View.GONE);
                        }
                    } else {
                        Toast.makeText(context, "请选择正确的比赛时间", Toast.LENGTH_SHORT).show();
                        if (type == 0) {
                            startTime = 0;
                        } else {
                            endTime = 0;
                        }
                    }
                } else {
                    if (type == 0) {
                        etStartTime.setText(DateUtil.DateToStr(date));
                        imageStart.setVisibility(View.GONE);
                    } else if (type == 1) {
                        etEndTime.setText(DateUtil.DateToStr(date));
                        imageEnd.setVisibility(View.GONE);
                    }
                }

            }
        }).setTitleText("")
                .setType(new boolean[]{true, true, true, true, true, false})// 默认全部显示
                .setDividerColor(Color.BLACK)
                .setOutSideCancelable(true)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setSubmitColor(Color.parseColor("#333333"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#666666"))//取消按钮文字颜色
                .setLineSpacingMultiplier(2.0f)
                .setLabel("年", "月", "日", "时", "分", "")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();
    }

    /**
     * 城市选择
     */
    public void showPickerView() {

        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                provinceName = options1Items.get(options1).getPickerViewText();
                cityName = options2Items.get(options1).get(options2);
                districtName = options3Items.get(options1).get(options2).get(options3);
                num1 = options1;
                num2 = options2;
                num3 = options3;
                ProvinceBean provinceBean = options1Items.get(options1);

                if (cityName.equals("全部")) {
                    cityName = "";
                    perimeter = Double.parseDouble(options1Items.get(options1).getProvincePerimeter());
                    code = provinceBean.getProvinceCode();
                } else if (districtName.equals("全部")) {
                    ProvinceBean.CitylistBean citylistBean = provinceBean.getCitylist().get(options2);
                    districtName = "";
                    perimeter = Double.parseDouble(citylistBean.getCityPerimeter());
                    code = citylistBean.getCityCode();

                } else {
                    ProvinceBean.AreaListBean areaListBean = options1Items.get(options1).getCitylist().get(options2).getAreaList().get(options3);
                    perimeter = Double.parseDouble(areaListBean.getAreaPerimeter());
                    code = areaListBean.getAreaCode();
                }
                selectCity = provinceName + cityName + districtName;
                etArea.setText(selectCity.replace("全部", ""));
                if (!TextUtils.isEmpty(selectCity) && perimeter != 0) {
                    imageArea.setVisibility(View.GONE);
                    tvAreaDistance.setVisibility(View.VISIBLE);
                    tvAreaDistance.setText("行政区总里程：" + decimalFormat.format(perimeter) + "公里");
                }
                showUserDis();


            }
        }).setTitleText(" ")
                .setDividerColor(Color.BLACK)
                .setOutSideCancelable(true)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setSubmitColor(Color.parseColor("#333333"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#666666"))//取消按钮文字颜色
                .setLineSpacingMultiplier(2.0f)
                .setSelectOptions(num1, num2, num3)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    /**
     * 显示 每个人跑的公里
     */
    private void showUserDis() {
        if (!TextUtils.isEmpty(num) && perimeter != 0) {
            tvUserDistance.setVisibility(View.VISIBLE);
            tvUserDistance.setText("平均每人需跑里程：" + decimalFormat.format(perimeter / Integer.parseInt(num)) + "公里");
        } else
            tvUserDistance.setVisibility(View.GONE);
    }
}
